=begin pod :tag<perl6>

=TITLE Variables

=SUBTITLE Variables in Perl 6

Variable names can start with or without a special character called a I<sigil>, followed
optionally by a second special character named I<twigil> and then an
L<identifier|/language/syntax#Identifiers>. Variables are symbolic names for values or
L<containers|/language/containers>. Variable declarations or assignment of
values may create a container on the fly.

=head1 Sigils
X<|$ (sigil),@ (sigil),% (sigil),& (sigil)>

There are four sigils. The scalar-sigil C<$>, the positional-sigil C<@>, the
associative-sigil C<%> and the callable-sigil C<&>.

Sigils provide a link between syntax, the type system and
L<containers|/language/containers>. They provide a shortcut for the most common
type constraints when declaring variables and serve as markers for
L<string interpolation|/language/quoting#Interpolation:_qq>. The
L<positional-sigil|/language/containers#Flattening,_items_and_containers> and
the L<associative-sigil|/language/containers#Flattening,_items_and_containers>
provide type constraint that enforce a base type
L<subscripts|/language/subscripts#Custom_types> require to know what methods to
dispatch to. The L<callable-sigil|/language/containers#Callable_containers>
does the same for function calls. The latter also tells the compiler where
parentheses for calls can be omitted. The positional and associative-sigil also
simplify assignment by flattening by default.

=begin table

    Sigil   Type constraint              Default type  Assignment  Examples
    =====   ===============              ============  ==========  ========
    $       Mu (no type constraint)      Any           item        Int, Str, Array, Hash
    @       Positional                   Array         list        List, Array, Range, Buf
    %       Associative                  Hash          list        Hash, Map, Pair
    &       Callable                     Callable      item        Sub, Method, Block, Routine

=end table

Examples:

    my $square = 9 ** 2;
    my @array  = 1, 2, 3;   # Array variable with three elements
    my %hash   = London => 'UK', Berlin => 'Germany';

X<|is (container type)>
The container type can be set with C<is> in a declaration.

    class FailHash is Hash {
        has Bool $!final = False;
        multi method AT-KEY ( ::?CLASS:D: Str:D \key ){
            fail X::OutOfRange.new(:what("Hash key"), :got(key), :range(self.keys)) if $!final && !self.EXISTS-KEY(key);
            callsame
        }

        method finalize() {
            $!final = True
        }
    }

    my %h is FailHash = oranges => "round", bananas => "bendy";
    say %h<oranges>;
    # OUTPUT: «round␤»
    %h.finalize;
    say %h<cherry>;
    CATCH { default { put .^name, ': ', .Str } }
    # OUTPUT: «X::OutOfRange: Hash key out of range. Is: cherry, should be in (oranges bananas)»

For information on variables without sigils, see
L<sigilless variables|#Sigilless variables>.

=head2 Item and List Assignment

There are two types of variable assignment, I<item assignment> and I<list
assignment>.  Both use the equal sign C<=> as operator. The syntax of the
left-hand side determines whether an C<=> means item or list assignment.

Item assignment places the value from the right-hand side into the variable
(container) on the left.

List assignment leaves the choice of what to do to the variable on the left.

For example, L<Array> variables (C<@> sigil) empty themselves on list
assignment and then put all the values from the right-hand side into
themselves.

The type of assignment (item or list) is decided by the first context
seen in the current expression or declarator:

    my $foo = 5;            # item assignment
    say $foo.perl;          # OUTPUT: «5␤»

    my @bar = 7, 9;         # list assignment
    say @bar.^name;         # OUTPUT: «Array␤»
    say @bar.perl;          # OUTPUT: «[7, 9]␤»

    (my $baz) = 11, 13;     # list assignment
    say $baz.^name;         # OUTPUT: «List␤»
    say $baz.perl;          # OUTPUT: «$(11, 13)␤»

Thus, the behavior of an assignment contained within a list assignment depends
on the expression or declarator that contains it.

For instance, if the internal assignment is a declarator, item assignment
is used, which has tighter precedence than both the comma and the list
assignment:

    my @array;
    @array = my $num = 42, "str";   # item assignment: uses declarator
    say @array.perl;                # OUTPUT: «[42, "str"]␤» (an Array)
    say $num.perl;                  # OUTPUT: «42␤» (a Num)

Similarly, if the internal assignment is an expression that is being
used as an initializer for a declarator, the context of the internal
expression determines the assignment type:

    my $num;
    my @array = $num = 42, "str";    # item assignment: uses expression
    say @array.perl;                 # OUTPUT: «[42, "str"]␤» (an Array)
    say $num.perl;                   # OUTPUT: «42␤» (a Num)

    my ( @foo, $bar );
    @foo = ($bar) = 42, "str";       # list assignment: uses parentheses
    say @foo.perl;                   # OUTPUT: «[(42, "str"),]␤» (an Array)
    say $bar.perl;                   # OUTPUT: «$(42, "str")␤» (a List)#

However, if the internal assignment is neither a declarator nor an
expression, but is part of a larger expression, the context of the
larger expression determines the assignment type:

    my ( @array, $num );
    @array = $num = 42, "str";    # list assignment
    say @array.perl;              # OUTPUT: «[42, "str"]␤»
    say $num.perl;                # OUTPUT: «42␤»

The assignment expression is parsed as C<@array = (($num = 42), "str")>,
because item assignment has tighter precedence than the comma.

See L<operators|/language/operators> for more details on precedence.

=head2 Sigilless variables
X<|\ (sigilless variables)>

Using the C<\> prefix, it's possible to create variables that do not
have a sigil:

    my \degrees = pi / 180;
    my \θ       = 15 * degrees;

Note that sigilless variable do not have associated  L<containers|/language/containers>. This means C<degrees>
and C<θ>, above, actually directly represent C<Num>s. To illustrate, try
assigning to one after you've defined it:

=begin code :skip-test
θ = 3; # Dies with the error "Cannot modify an immutable Num"
=end code

Sigilless variables do not enforce context, so they can be used to pass
something on as-is:

    sub logged(&f, |args) {
        say('Calling ' ~ &f.name ~ ' with arguments ' ~ args.perl);
        my \result = f(|args);
        #  ^^^^^^^ not enforcing any context here
        say(&f.name ~ ' returned ' ~ result.perl);
        return |result;
    }

Sigilless variables can also be used for binding.
See L<Binding|/language/containers#Binding> for more information.

=head1 Twigils
X<|Twigil>

Twigils influence the scoping of a variable; however, they
have no influence over whether the primary sigil interpolates. That is, if
C<$a> interpolates, so do C<$^a>, C<$*a>, C<$=a>, C<$?a>, C<$.a>, etc.  It
only depends on the C<$>.

=begin table

    Twigil  Scope
    ======  =====
     none   Based only on declarator
     *      Dynamic
     ?      Compile-time variable
     !      Attribute (class member)
     .      Method (not really a variable)
     <      Index into match object (not really a variable)
     ^      Self-declared formal positional parameter
     :      Self-declared formal named parameter
     =      Pod variables
     ~      The sublanguage seen by the parser at this lexical spot

=end table

=head2 The C<*> Twigil
X<|$*>

Dynamic variables are looked up through the caller, not through the outer
scope. Look at the example below.

I<Note:> So far, if you use rakudo perl6, the example below cannot run
correctly in REPL. You can try it by copy-pasting it into a file, then
run the file.

    =begin code
    my $lexical   = 1;
    my $*dynamic1 = 10;
    my $*dynamic2 = 100;

    sub say-all() {
        say "$lexical, $*dynamic1, $*dynamic2";
    }

    say-all();    # OUTPUT: 1, 10, 100

    {
        my $lexical   = 2;
        my $*dynamic1 = 11;
        $*dynamic2    = 101;

        say-all(); # OUTPUT: 1, 11, 101
    }

    say-all();  # OUTPUT: 1, 10, 101
    =end code

The first time C<&say-all> is called, it prints "C<1, 10, 100>" just as one
would expect. The second time though, it prints "C<1, 11, 101>". This is
because C<$lexical> isn't looked up in the caller's scope but in the scope
C<&say-all> was defined in. The two dynamic variables are looked up in the
caller's scope and therefore have the values C<11> and C<101>. The third
time C<&say-all> is called C<$*dynamic1> isn't C<11> anymore, but
C<$*dynamic2> is still C<101>. This stems from the fact that we declared a
new dynamic variable C<$*dynamic1> in the block and did not assign to the
old variable as we did with C<$*dynamic2>.

The dynamic variables differ from other variable types in that referring
to an undeclared dynamic variable is not a compile time error but a
runtime L<failure|/type/Failure>, so a dynamic variable can be used
undeclared as long as it's checked for definedness or used in a
boolean context before using it for anything else:

    =begin code
    sub foo() {
        $*FOO // 'foo';
    }

    say foo; # OUTPUT: «foo␤»

    my $*FOO = 'bar';

    say foo; # OUTPUT: «bar␤»
    =end code

Dynamic variables can have lexical scope when declared with C<my> or package scope when declared with C<our>. Dynamic resolution and resolution through symbol tables introduced with C<our> are two orthogonal issues.


=head2 The C<?> Twigil
X<|$?>

Compile-time variables may be addressed via the C<?> twigil. They are known
to the compiler and may not be modified after being compiled in. A popular
example for this is:

    say "$?FILE: $?LINE"; # OUTPUT: "hello.pl: 23"
                          # if this is the line 23 of a
                          # file named "hello.pl"

For a list of these special variables, see
L<compile-time variables|/language/variables#Compile-time_variables>.

=head2 The C<!> Twigil
X<|$!>

L<Attributes|/language/objects#Attributes> are variables that exist per instance
of a class. They may be directly accessed from within the class via C<!>:

    my class Point {
        has $.x;
        has $.y;

        method Str() {
            "($!x, $!y)"
        }
    }

Note how the attributes are declared as C<$.x> and C<$.y> but are still
accessed via C<$!x> and C<$!y>. This is because in Perl 6 all attributes are
private and can be directly accessed within the class by using
C<$!attribute-name>. Perl 6 may automatically generate accessor methods for
you though. For more details on objects, classes and their attributes see
L<object orientation|/language/objects>.


=head2 The C<.> Twigil
X<|$.>

The C<.> twigil isn't really for variables at all. In fact, something along
the lines of

    my class Point {
        has $.x;
        has $.y;

        method Str() {
            "($.x, $.y)" # note that we use the . instead of ! this time
        }
    }

just calls the methods C<x> and C<y> on C<self>, which are automatically
generated for you because you used the C<.> twigil when the attributes were
declared.  Note, however, that subclasses may override those methods. If you
don't want this to happen, use C<$!x> and C<$!y> instead.

The fact that the C<.> twigil does a method call implies that the following
is also possible:

    class SaySomething {
        method a() { say "a"; }
        method b() { $.a; }
    }

    SaySomething.b; # OUTPUT: «a␤»

For more details on objects, classes and their attributes and methods see
L<object orientation|/language/objects>.

=head2 The C<^> Twigil
X<|$^>

The C<^> twigil declares a formal positional parameter to blocks or
subroutines.  Variables of the form C<$^variable> are a type of placeholder
variable. They may be used in bare blocks to declare formal parameters to
that block. So the block in the code

    my @powers-of-three = 1,3,9…100;
    say reduce { $^b - $^a }, 0, |@powers-of-three;
    # OUTPUT: «61␤»

has two formal parameters, namely C<$a> and C<$b>. Note that even though C<$^b>
appears before C<$^a> in the code, C<$^a> is still the first formal parameter
to that block. This is because the placeholder variables are sorted in Unicode
order. If you have self-declared a parameter using C<$^a> once, you may refer
to it using only C<$a> thereafter.

Although it is possible to use nearly any valid identifier as a placeholder
variable, it is recommended to use short names or ones that can be trivially
understood in the correct order, to avoid surprise on behalf of the reader.

Normal blocks and subroutines may also make use of placeholder variables but only if they do
not have an explicit parameter list.

=begin code :skip-test
sub say-it    { say $^a; } # valid
sub say-it()  { say $^a; } # invalid
              { say $^a; } # valid
-> $x, $y, $x { say $^a; } # invalid
=end code

Placeholder variables cannot have type constraints or a variable name with a
single upper-case letter (this is disallowed to enable catching some
Perl5-isms).

=head2 The C<:> Twigil
X<|$:>

The C<:> twigil declares a formal named parameter to a block or subroutine.
Variables declared using this form are a type of placeholder variable too.
Therefore the same things that apply to variables declared using the C<^>
twigil also apply here (with the exception that they are not positional and
therefore not ordered using Unicode order, of course). So this:

    say { $:add ?? $^a + $^b !! $^a - $^b }( 4, 5 ) :!add
    # OUTPUT: «-1␤»

See L<^> for more details about placeholder variables.

=head2 The C<=> Twigil
X<|$=>

The C<=> twigil is used to access Pod variables. Every Pod block in the
current file can be accessed via a Pod object, such as C<$=data>,
C<$=SYNOPSIS> or C<=UserBlock>. That is: a variable with the same name of
the desired block and a C<=> twigil.

  =begin code :skip-test
    =begin code
    =begin Foo
    ...
    =end Foo

    #after that, $=Foo gives you all Foo-Pod-blocks
    =end code
  =end code

You may access the Pod tree which contains all Pod structures as a
hierarchical data structure through C<$=pod>.

Note that all those C<$=someBlockName> support the C<Positional> and the
C<Associative> roles.

=head2 The C<~> Twigil
X<|$~>

The C<~> twigil is for referring to sublanguages (called slangs). The
following are useful:

X<|$~MAIN>X<|$~Quote>X<|$~Quasi>X<|$~Regex>X<|$~Trans>X<|$~P5Regex>

=begin table
    $~MAIN       the current main language (e.g. Perl statements)
    $~Quote      the current root of quoting language
    $~Quasi      the current root of quasiquoting language
    $~Regex      the current root of regex language
    $~Trans      the current root of transliteration language
    $~P5Regex    the current root of the Perl 5 regex language
=end table

You C<augment> these languages in your current lexical scope.

=begin code :skip-test
use MONKEY-TYPING;
augment slang Regex {  # derive from $~Regex and then modify $~Regex
    token backslash:std<\Y> { YY };
}
=end code

=head1 Variable Declarators and Scope

Most of the time it's enough to create a new variable using the C<my>
keyword:

    my $amazing-variable = "World";
    say "Hello $amazing-variable!"; # OUTPUT: «Hello World!␤»

However, there are many declarators that change the details of scoping
beyond what L<#Twigils> can do.

=for table
    Declarator    Effect
    ==========    ======
    my            Introduces lexically scoped names
    our           Introduces package-scoped names
    has           Introduces attribute names
    anon          Introduces names that are private to the construct
    state         Introduces lexically scoped but persistent names
    augment       Adds definitions to an existing name
    supersede     Replaces definitions of an existing name

There are also two prefixes that resemble declarators but act on
predefined variables:

=for table
    Prefix  Effect
    ======  ======
    temp    Restores a variable's value at the end of scope
    let     Restores a variable's value at the end of scope if the block exits unsuccessfully

=head2 The C<my> Declarator

Declaring a variable with C<my> gives it lexical scope. This means it only
exists within the current block. For example:

=begin code :skip-test
{
    my $foo = "bar";
    say $foo; # OUTPUT: «"bar"␤»
}
say $foo; # Exception! "Variable '$foo' is not declared"
=end code

This dies because C<$foo> is only defined as long as we are in the same
scope.

Additionally, lexical scoping means that variables can be temporarily
redefined in a new scope:

    my $location = "outside";

    sub outer-location {
        # Not redefined:
        say $location;
    }

    outer-location; # OUTPUT: «outside␤»

    sub in-building {
        my $location = "inside";
        say $location;
    }

    in-building;    # OUTPUT: «inside␤»

    outer-location; # OUTPUT: «outside␤»

If a variable has been redefined, any code that referenced the outer
variable will continue to reference the outer variable. So here,
C<&outer-location> still prints the outer C<$location>:

=begin code :skip-test
sub new-location {
    my $location = "nowhere";
    outer-location;
}

new-location; # OUTPUT: «outside␤»
=end code

To make C<new-location()> print C<nowhere>, make C<$location> a dynamic
variable using L<the * twigil|#The_*_Twigil>. This twigil makes the compiler look up the symbol in the calling scope instead of the outer scope after trying the local scope.

C<my> is the default scope for subroutines, so C<my sub x() {}> and
C<sub x() {}> do exactly the same thing.

=head2 The C<our> Declarator

C<our> variables work just like C<my> variables, except that they also
introduce an alias into the symbol table.

    module M {
        our $Var;
        # $Var available here
    }

    # Available as $M::Var here.

=head2 Declaring a list of variables

The declarators C<my> and C<our> take a list of variables in parentheses as argument to declare more than one variable at a time.

    my (@a, $s, %h);

This can be used in conjunction with X«destructuring assignment». Any
assignment to such a list will take the number of elements provided in the left
list and assign corresponding values from the right list to them. Any missing
elements are left will result in undefined values according to the type of the
variables.

    my (Str $a, Str $b, Int $c) = <a b>;
    say [$a, $b, $c].perl;
    # OUTPUT: «["a", "b", Int]␤»

To destructure a list into a single value, create a list literal with one element
by using C<($var,)>. When used with a variable declarator, providing
parentheses around a single variable is sufficient.

    sub f { 1,2,3 };
    my ($a) = f;
    say $a.perl;
    # OUTPUT: «1␤»

To skip elements in the list use the anonymous state variable C<$>.

    my ($,$a,$,%h) = ('a', 'b', [1,2,3], {:1th});
    say [$a, %h].perl;
    # OUTPUT: «["b", {:th(1)}]␤»

=head2 The C<has> Declarator

C<has> scopes attributes to instances of a class or role, and methods to
classes or roles. C<has> is implied for methods, so C<has method x() {}>
and C<method x() {}> do the same thing.

See L<object orientation|/language/objects> for more documentation and some
examples.

=head2 The C<anon> Declarator

The C<anon> declarator prevents a symbol from getting installed in the lexical
scope, the method table and everywhere else.

For example, you can use it to declare subroutines which know their own name,
but still aren't installed in a scope:

    my %operations =
        half   => anon sub half($x) { $x / 2 },
        square => anon sub square($x) { $x * $x },
        ;
    say %operations<square>.name;       # square
    say %operations<square>(8);         # 64

=head2 The C<state> Declarator

C<state> declares lexically scoped variables, just like C<my>. However,
initialization happens exactly once the first time the initialization
is encountered in the normal flow of execution. Thus, state variables
will retain their value across multiple executions of the enclosing
block or routine.

Therefore, the subroutine

    sub a {
        state @x;
        state $l = 'A';
        @x.push($l++);
    };

    say a for 1..6;

will continue to increment C<$l> and append it to C<@x> each time it is
called. So it will output:

=begin code :skip-test

[A]
[A B]
[A B C]
[A B C D]
[A B C D E]
[A B C D E F]

=end code

This works per "clone" of the containing code object, as in this example:

    ({ state $i = 1; $i++.say; } xx 3).map: {$_(), $_()}; # says 1 then 2 thrice

Note that this is B<not> a thread-safe construct when the same clone of the same
block is run by multiple threads.  Also remember that methods only have one
clone per class, not per object.


As with C<my>, declaring multiple C<state> variables must be placed
in parentheses and for declaring a single variable, parentheses may
be omitted.

Many operators come with implicit binding which can lead to actions at a distance.

Use C<.clone> or coercion to create a new container that can be bound to.

    my @a;
    my @a-cloned;
    sub f() {
        state $i;
        $i++;
        @a\      .push: "k$i" => $i;
        @a-cloned.push: "k$i" => $i.clone;
    };

    f for 1..3;
    say @a;        # OUTPUT: «[k1 => 3 k2 => 3 k3 => 3]␤»
    say @a-cloned; # OUTPUT: «[k1 => 1 k2 => 2 k3 => 3]␤»

State variables are shared between all threads. The result can be unexpected.

    sub code(){ state $i = 0; say ++$i; $i };
    await
        start { loop { last if code() >= 5 } },
        start { loop { last if code() >= 5 } };

    # OUTPUT: «1␤2␤3␤4␤4␤3␤5␤»
    # OUTPUT: «2␤1␤3␤4␤5␤»
    # many other more or less odd variations can be produced

=head3 The C<$> Variable
X<|anon state variables>X<|nameless variables>

In addition to explicitly declared named state variables, C<$> can be used
as an anonymous state variable without an explicit C<state> declaration.

    say "1-a 2-b 3-c".subst(:g, /\d/, {<one two three>[$++]});
    # OUTPUT: «one-a two-b three-c␤»

Furthermore, state variables can be used outside of subroutines. You
could, for example, use C<$> in a one-liner to number the lines in a file.

=begin code :skip-test
perl6 -ne 'say ++$ ~ " $_"' example.txt
=end code

Each reference to C<$> within a lexical scope is in effect a separate
variable.

=begin code :skip-test
perl6 -e '{ say ++$; say $++  } for ^5'
# OUTPUT: «1␤0␤2␤1␤3␤2␤4␤3␤5␤4␤»
=end code

If you need to use the value of $ more than once in a scope, it should be
copied to a new variable.

    sub foo() {
        given ++$ {
            when 1 {
                say "one";
            }
            when 2 {
                say "two";
            }
            when 3 {
                say "three";
            }
            default {
                say "many";
            }
        }
    }

    foo() for ^3;
    # OUTPUT: «one␤two␤three␤»

Note that the implicit state declarator is only applied to the variable
itself, not the expression that may contain an initializer. If the
initializer has to be called exactly once, the C<state> declarator has to be
provided.

    =begin code :skip-test
    subset DynInt where $ = ::('Int'); # the initializer will be called for each type check
    subset DynInt where state $ = ::('Int'); # the initializer is called once, this is a proper cache
    =end code

=head3 The C<@> Variable

Similar to the C<$> variable, there is also a L<Positional>
anonymous state variable C<@>.

    sub foo($x) {
        say (@).push($x);
    }

    foo($_) for ^3;

    # OUTPUT: «[0]
    #          [0 1]
    #          [0 1 2]␤»

The C<@> here is parenthesized in order to disambiguate the expression
from a class member variable named C<@.push>.  Indexed access doesn't
require this disambiguation but you will need to copy the value in order
to do anything useful with it.

    sub foo($x) {
        my $v = @;
        $v[$x] = $x;
        say $v;
    }

    foo($_) for ^3;

    # OUTPUT: «[0]
    #          [0 1]
    #          [0 1 2]␤»

As with C<$>, each mention of C<@> in a scope introduces a new anonymous
array.

=head3 The C<%> Variable

In addition, there's an L<Associative> anonymous state variable C<%>.

    sub foo($x) {
        say (%).push($x => $x);
    }

    foo($_) for ^3;

    # OUTPUT: «{0 => 0}
    #          {0 => 0, 1 => 1}
    #          {0 => 0, 1 => 1, 2 => 2}␤»

The same caveat about disambiguation applies. As you may expect, indexed
access is also possible (with copying to make it useful).

    sub foo($x) {
        my $v = %;
        $v{$x} = $x;
        say $v;
    }

    foo($_) for ^3;

    # OUTPUT: «{0 => 0}
    #          {0 => 0, 1 => 1}
    #          {0 => 0, 1 => 1, 2 => 2}␤»

As with the other anonymous state variables, each mention of C<%> within a
given scope will effectively introduce a separate variable.

=head2 The C<augment> Declarator

With C<augment>, you can add attributes and methods to existing classes and
grammars, provided you activated the C<MONKEY-TYPING> pragma first.

Since classes are usually C<our> scoped, and thus global, this means modifying
global state, which is strongly discouraged. For almost all situations, there
are better solutions.

    # don't do this
    use MONKEY-TYPING;
    augment class Int {
        method is-answer { self == 42 }
    }
    say 42.is-answer;       # OUTPUT: «True␤»

(In this case, the better solution would be to use a
L<function|/language/functions>).

=head2 The C<temp> Prefix

Like C<my>, C<temp> restores the old value of a variable at the end of its
scope. However, C<temp> does not create a new variable.

    my $in = 0; # temp will "entangle" the global variable with the call stack
                # that keeps the calls at the bottom in order.
    sub f(*@c) {
        (temp $in)++;
         "<f>\n"
         ~ @c».indent($in).join("\n")
         ~ (+@c ?? "\n" !! "")
         ~ '</f>'
    };
    sub g(*@c) {
        (temp $in)++;
        "<g>\n"
        ~ @c».indent($in).join("\n")
        ~ (+@c ?? "\n" !! "")
        ~ "</g>"
    };
    print g(g(f(g()), g(), f()));

    # OUTPUT: «<g>
    #           <g>
    #            <f>
    #             <g>
    #             </g>
    #            </f>
    #            <g>
    #            </g>
    #            <f>
    #            </f>
    #           </g>
    #          </g>␤»

=head2 The C<let> Prefix

Restores the previous value if the block exits unsuccessfully. A
successful exit means the block returned a defined value or a list.

    my $answer = 42;

    {
        let $answer = 84;
        die if not Bool.pick;
        CATCH {
            default { say "it's been reset :(" }
        }
        say "we made it 84 sticks!";
    }

    say $answer;

In the above case, if the C<Bool.pick> returns true, the answer will
stay as 84 because the block returns a defined value (C<say> returns
true). Otherwise the C<die> statement will cause the block to exit
unsuccessfully, resetting the answer to 42.

=comment this is duplicated in operators.pod

=head1 Type Constraints and Initialization

Variables have a type constraint via the L<container|/language/containers> they
are bound to, which goes between the declarator and the variable name. The
default type constraint is L<Mu|/type/Mu>. You can also use the trait
L<of|/type/Variable#trait_of> to set a type constraint.

    my Int $x = 42;
    $x = 'a string';
    CATCH { default { put .^name, ': ', .Str } }
    # OUTPUT: «X::TypeCheck::Assignment: Type check failed in assignment to $x; expected Int but got Str ("a string")␤»

If a scalar variable has a type constraint but no initial value, it's
initialized with the type object of the default value of the container it's bound to.

    my Int $x;
    say $x.^name;       # OUTPUT: «Int␤»
    say $x.defined;     # OUTPUT: «False␤»

Scalar variables without an explicit type constraint are typed as
L<Mu|/type/Mu> but default to the L<Any|/type/Any> type object.

Variables with the C<@> sigil are initialized with an empty
L<Array|/type/Array>; variables with the C<%> sigil are initialized with an
empty L<Hash|/type/Hash>.

The default value of a variable can be set with the C<is default> trait, and
re-applied by assigning C<Nil> to it:

    my Real $product is default(1);
    say $product;                       # OUTPUT: «1␤»
    $product *= 5;
    say $product;                       # OUTPUT: «5␤»
    $product = Nil;
    say $product;                       # OUTPUT: «1␤»

=head2 Default Defined Variables Pragma

To force all variables to have a definedness constraint, use the pragma C<use
variables :D>. The pragma is lexically scoped and can be switched off with C<use
variables :_>.

=begin code :skip-test
use variables :D;
my Int $i;
# OUTPUT: «===SORRY!=== Error while compiling <tmp>␤Variable definition of type Int:D (implicit :D by pragma) requires an initializer ...
my Int $i = 1; # that works
{ use variables :_; my Int $i; } # switch it off in this block
=end code

Note that assigning L<Nil|/type/Nil> will revert the variable to its
default value. The default value of a defined constraint type is the type
appended with C<:D> (e.g. C<Int:D>). That means a definedness constraint is no
guarantee of definedness. This only applies to variable initializers, not to
L<Signature|/type/Signature>s. or subsequent assignments to a variable.

=head1 Special Variables

Perl 6 attempts to use long, descriptive names for special
variables. There are only three special variables that are extra
short.

=head2 Pre-defined lexical variables

There are three special variables that are available in every block:

=begin table

    Variable    Meaning

    $_          topic variable
    $/          regex match
    $!          exceptions

=end table

=head3 The C<$_> Variable

C<$_> is the topic variable. It's the default parameter for blocks that do
not have an explicit signature, so constructs like C<for @array { ... }> and
C<given $var { ... }> bind to C<$_> by invoking the block.

    for <a b c> { say $_ }  # sets $_ to 'a', 'b' and 'c' in turn
    say $_ for <a b c>;     # same, even though it's not a block
    given 'a'   { say $_ }  # sets $_ to 'a'
    say $_ given 'a';       # same, even though it's not a block

C<CATCH> blocks set C<$_> to the exception that was caught. The C<~~>
smart-match operator sets C<$_> on the right-hand side expression to the
value of the left-hand side.

Calling a method on C<$_> can be shortened by leaving off the variable name:

    .say;                   # same as $_.say

C<m/regex/> and C</regex/> regex matches and C<s/regex/subst/> substitutions
work on C<$_>:

    say "Looking for strings with non-alphabetic characters...";
    for <ab:c d$e fgh ij*> {
        .say if m/<-alpha>/;
    }

    # OUTPUT: «Looking for strings with non-alphabetic characters...
    #          ab:c
    #          d$e
    #          ij*␤»

=head3 The C<$/> Variable

C<$/> is the match variable. It stores the result of the last L<Regex|/language/regexes>
match and so usually contains objects of type L<Match>.

    'abc 12' ~~ /\w+/;  # sets $/ to a Match object
    say $/.Str;         # OUTPUT: «abc␤»

The C<Grammar.parse> method also sets the caller's C<$/> to the resulting
L<Match> object.  For the following code:

=begin code :skip-test
use XML::Grammar; # zef install XML
XML::Grammar.parse("<p>some text</p>");
say $/;

# OUTPUT: «｢<p>some text</p>｣
#           root => ｢<p>some text</p>｣
#            name => ｢p｣
#            child => ｢some text｣
#             text => ｢some text｣
#             textnode => ｢some text｣
#           element => ｢<p>some text</p>｣
#            name => ｢p｣
#            child => ｢some text｣
#             text => ｢some text｣
#             textnode => ｢some text｣␤»
=end code

=head4 X«Positional Attributes|variable,$0;variable,$1;variable,@()»

C<$/> can have positional attributes if the L<Regex|/language/regexes> had
capture-groups in it, which are just formed with parentheses.

    'abbbbbcdddddeffg' ~~ / a (b+) c (d+ef+) g /;
    say $/[0]; # OUTPUT: «｢bbbbb｣␤»
    say $/[1]; # OUTPUT: «｢dddddeff｣␤»

These can also be accessed by the shortcuts C<$0>, C<$1>, C<$2>, etc.

    say $0; # OUTPUT: «｢bbbbb｣␤»
    say $1; # OUTPUT: «｢dddddeff｣␤»

To get all of the positional attributes, any of C<$/.list>, C<@$/>, or
C<@()> can be used.

    say @().join; # OUTPUT: «bbbbbdddddeff␤»

=head4 X«Named Attributes|variable,$<named>;variable,%()»

C<$/> can have named attributes if the L<Regex|/language/regexes> had named
capture-groups in it, or if the Regex called out to another Regex.

    'I.... see?' ~~ / \w+ $<punctuation>=[ <-[\w\s]>+ ] \s* $<final-word> = [ \w+ . ] /;
    say $/<punctuation>; # OUTPUT: «｢....｣␤»
    say $/<final-word>;  # OUTPUT: «｢see?｣␤»

These can also be accessed by the shortcut C«$<named>».

    say $<punctuation>; # OUTPUT: «｢....｣␤»
    say $<final-word>;  # OUTPUT: «｢see?｣␤»

To get all of the named attributes, any of C<$/.hash>, C<%$/>, or C<%()> can
be used.

    say %().join;       # OUTPUT: «"punctuation     ....final-word  see?"␤»

=head3 The C<$!> Variable

C<$!> is the error variable. If a C<try> block or statement prefix catches
an exception, that exception is stored in C<$!>. If no exception was caught,
C<$!> is set to the C<Any> type object.

Note that C<CATCH> blocks I<do not> set C<$!>. Rather they set C<$_> inside
the block to the caught exception.

=head2 Compile-time variables

X<|$?FILE>X<|$?LINE>X<|::?CLASS>X<|&?ROUTINE>X<|&?BLOCK>X<|%?LANG>X<|%?RESOURCES>

All compile time variables have a question mark as part of the twigil.
Being I<compile time> they cannot
be changed at run-time, however they are valuable in order to introspect
the program.
The most common compile time variables are the following:

=for table
    $?FILE         Which file am I in?
    $?LINE         Which line am I at?
    ::?CLASS       Which class am I in?
    %?LANG         What is the current set of interwoven languages?
    %?RESOURCES    The files associated with the "Distribution" of the current compilation unit.

=head3 Other compile-time variables:

X<|$?PACKAGE>X<|$?MODULE>X<|$?CLASS>X<|$?ROLE>
X<|$?GRAMMAR>X<|$?TABSTOP>X<|$?NL>X<|$?ENC>

The following compile time variables allow for a deeper introspection:

=for table
    $?PACKAGE   Which package am I in?
    $?MODULE    Which module am I in?
    $?CLASS     Which class am I in? (as variable)
    $?ROLE      Which role am I in? (as variable)
    $?GRAMMAR   Which grammar am I in?
    $?TABSTOP   How many spaces is a tab in a heredoc or virtual margin?
    $?NL        What a vertical newline "\n" means: LF, CR or CRLF
    $?ENC       Default encoding of various IO methods, e.g., Str.encode, Buf.decode

With particular regard to the C<$?NL>, see the  L<newline pragma|/language/pragmas>.


=head3 X<&?ROUTINE|&?ROUTINE>

The compile time variable C<&?ROUTINE> provides introspection about
which routine the program is actually within. It returns an instance
of L<Sub|/type/Sub> attached to the current routine.
It does support the method C<.name> to obtain
the name of the called routine, as well as C<.signature> and others
method related to C<Sub>:


    sub awesome-sub { say &?ROUTINE.name }
    awesome-sub # OUTPUT: awesome-sub

The special variable C<&?ROUTINE> allows also for recursion:

=begin code
my $counter = 10;
sub do-work {
    say 'Calling myself other ' ~ $counter-- ~ ' times';
    &?ROUTINE() if ( $counter > 0 );
}
do-work;
=end code

=head3 X<&?BLOCK|&?BLOCK>

The special compile variable C<?&BLOCK> behaves similarly to
C<?&ROUTINE> but it allows to introspect a single block of code.
It holds a L<Sub|/types/Sub> and allows for recursion within the
same block:

=begin code
for '.' {
    .Str.say when !.IO.d;
    .IO.dir()».&?BLOCK when .IO.d # lets recurse a little!
}
=end code


=head2 Dynamic variables

=comment There should be a better way get this table to be formatted
    properly, but if there's, Rakudo doesn't support it at the moment.

X<|$*ARGFILES>X<|@*ARGS>X<|$*IN>X<|$*OUT>X<|$*ERR>X<|%*ENV>X<|$*REPO>X<|$*TZ>
X<|$*CWD>X<|$*KERNEL>X<|$*DISTRO>X<|$*VM>X<|$*PERL>X<|$*PID>X<|$*PROGRAM-NAME>
X<|$*PROGRAM>X<|$*EXECUTABLE>X<|$*EXECUTABLE-NAME>X<|$*USER>X<|$*GROUP>
X<|$*HOME>X<|$*SPEC>X<|$*TMPDIR>X<|$*THREAD>X<|$*SCHEDULER>X<|$*USAGE>

=begin table
    $*ARGFILES        | An L<IO::ArgFiles> (an empty subclass of L<IO::CatHandle>)
                      | that uses C<@*ARGS> as source files, if
                      | it contains any files, or C<$*IN> otherwise. When C<$*IN>
                      | is used, its C<:nl-in>, C<:chomp>, C<:encoding>,
                      | and C<:bin> will be set on the L<IO::ArgFiles> object.
    ------------------+--------------------------------------------
    @*ARGS            | Arguments from the command line.
    ------------------+--------------------------------------------
    $*IN              | Standard input filehandle, AKA stdin
    ------------------+--------------------------------------------
    $*OUT             | Standard output filehandle, AKA stdout
    ------------------+--------------------------------------------
    $*ERR             | Standard error filehandle, AKA stderr
    ------------------+--------------------------------------------
    %*ENV             | Environment variables
    ------------------+--------------------------------------------
    $*REPO            | A variable holding information about modules installed/loaded
    ------------------+--------------------------------------------
    $*INIT-INSTANT    | An Instant object representing program startup time.
                      | In particular, this is when the core code starts up,
                      | so the value of $*INIT-INSTANT may be a few milliseconds
                      | earlier than C<INIT now> or even C<BEGIN now> executed
                      | in your program.
    ------------------+--------------------------------------------
    $*TZ              | The system's local timezone offset, as the number of B<seconds> from GMT
    ------------------+--------------------------------------------
    $*CWD             | The Current Working Directory.
    ------------------+--------------------------------------------
    $*KERNEL          | Which kernel am I running under?
    ------------------+--------------------------------------------
    $*DISTRO          | Which OS distribution am I running under? (e.g. C<say "Some sort of Windows" if $*DISTRO.is-win>)
    ------------------+--------------------------------------------
    $*VM              | Which virtual machine am I running under?
    ------------------+--------------------------------------------
    $*PERL            | Which Perl am I running under?
    ------------------+--------------------------------------------
    $*PID             | Process ID of the current process.
    ------------------+--------------------------------------------
    $*PROGRAM-NAME    | Path to the current executable as it was entered on the
                      | command line, or C<-e> if perl was invoked with the -e flag.
    ------------------+--------------------------------------------
    $*PROGRAM         | Location (in the form of an C<IO::Path> object) of the
                      | Perl program being executed.
    ------------------+--------------------------------------------
    &*EXIT            | Code that will be executed when doing an exit().  Intended
                      | to be used in situations where Perl 6 is embedded in
                      | another language runtime (such as Inline::Perl6 in Perl 5)
    ------------------+--------------------------------------------
    $*EXECUTABLE      | Absolute path of the perl executable that is currently running.
    ------------------+--------------------------------------------
    $*EXECUTABLE-NAME | The name of the perl executable that is currently running.
                      | (e.g. perl6-p, perl6-m, Niecza.exe)
                      | Favor $*EXECUTABLE because it's not guaranteed that the perl
                      | executable is in PATH.
    ------------------+--------------------------------------------
    $*USAGE           | Read-only. The default usage message generated from the
                      | signatures of MAIN subs available from inside
                      | sub MAIN and sub USAGE
    ------------------+--------------------------------------------
    $*USER            | The user that is running the program. It's an object
                      | that evaluates to "username (uid)".  It will evaluate
                      | to the username only if treated as a string and the
                      | numeric user id if treated as a number.
    ------------------+--------------------------------------------
    $*GROUP           | The primary group of the user who is running the program.
                      | It's an object that evaluates to "groupname (gid)".
                      | It will evaluate to the groupname only if treated as a
                      | string and the numeric group id if treated as a number.
    ------------------+--------------------------------------------
    $*HOME            | An L<IO::Path> object representing the "home directory"
                      | of the user that is running the program. Uses
                      |  C«%*ENV<HOME>» if set. On Windows, uses
                      |  C«%*ENV<HOMEDRIVE> ~ %*ENV<HOMEPATH>». If the
                      | home directory cannot be determined, it will be L<Any>
    ------------------+--------------------------------------------
    $*SPEC            | The appropriate L<IO::Spec> sub-class for the platform that
                      | the program is running on.
    ------------------+--------------------------------------------
    $*TMPDIR          | An L<IO::Path> object representing the "system temporary directory" as determined by L«C<.tmpdir IO::Spec::* method|/routine/tmpdir>»
    ------------------+--------------------------------------------
    $*TOLERANCE       | Used by the C<=~=> operator, and any operations that depend on it, to
                      | decide if two values are approximately equal. Defaults to 1e-15.
    ------------------+--------------------------------------------
    $*THREAD          | A L<Thread> object representing the currently executing thread.
    ------------------+--------------------------------------------
    $*SCHEDULER       | A L<ThreadPoolScheduler> object representing the current default
                      | scheduler. (see note below)
    ------------------+--------------------------------------------
    $*SAMPLER         | The current L<Telemetry::Sampler> used for making
                      | snapshots of system state.  Only available if
                      | L<Telemetry> has been loaded.
    ------------------+--------------------------------------------
=end table

Note on usage of $*SCHEDULER:

For the current Rakudo, by default this imposes a maximum of 16 threads on the methods
C<.hyper> and C<.race>. To change the maximum number of threads, either set the
environment variable RAKUDO_MAX_THREADS before running perl6 or create a scoped copy
with the default changed before using C<.hyper> or C<.race>:

    my $*SCHEDULER = ThreadPoolScheduler.new( max_threads => 64 );

This behavior is not tested in the spec tests and is subject to change.

=head1 Naming Conventions

It is helpful to know our naming conventions in order to understand what codes
do directly. However, there is not yet a conventions list covering anywhere.
Still we list several conventions that are widely held.

=item1 Subs and methods from the built-ins library try to have single-word names when a good one could be found. In cases where there are two or more words making up a name, they are separated by a "-".

=item1 Compounds are treated as a single word, thus C<substr>, C<subbuf>, and C<deepmap> (just like we write "starfish", not "star fish" in English).

=item1 Subs and methods that are automatically called for you at special times are written in uppercase. This includes the C<MAIN> sub, the C<AT-POS> and related methods for implementing container types, along with C<BUILD> and C<DESTROY>.

=item1 Type names are camel case, except for native types, which are lowercase. For the exception, you can remember it by: they are stored in a more compact way, so they names look smaller too.

=item1 Built-in dynamic variables and compile-time variables are always uppercase, such like C<$*OUT>, C<$?FILE>.

=item1 Methods from the MOP and other internals use "_" to separate multiple words, such like C<add_method>.

=end pod

# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6
